<?php

class login {
	function __construct() {
		if(!$this->has_access()) {
			if($_POST['username'] && $_POST['password']) {
				if(!$this->is_banned()) {
					$username = mysql_real_escape_string($_POST['username']);
					$password = mysql_real_escape_string($_POST['password']);
					
					$sql = "SELECT * FROM users WHERE username='".$username."'
							AND password = SHA1('".$password."')";
					$result = mysql_query($sql);

					if(mysql_num_rows($result) == 1) {
						$this->authorize($username);
						$this->save_login('login');
						header('Location: ../account/');
					} else {
						$this->save_login('failed');
						echo file_get_contents('../html/loginfail');
						$this->ban_warning($username);
					}
				} else {
					$this->save_login('banned');
					echo 'Max. login attempts reached';
				}
			}
		} 
	}	

	public function logout() {
		if(isset($_SESSION['user']) && $_SESSION['auth'] == 'yes') {
			$sql = "UPDATE logins SET logout=NOW() WHERE user='".$_SESSION['user']."' AND id='".$this->get_last_user_id()."'";
			mysql_query($sql);
			$_SESSION = array();
			session_destroy();
			echo "<b>Session is terminated - you are now logged out.</b><br>";
			echo "Redirecting..";
			header('Refresh: 2; url=http://www.norsof.org/laka/pa/frontend/');
		} else {
			echo "You are not logged in!";
		}
	}

	public function has_access() {
		if($_SESSION['auth'] == 'yes') {
			return true;
		}
	}

	public function authorize($username) {
		$_SESSION['user'] = $username;
		$_SESSION['auth'] = 'yes';
		$_SESSION['fail'] = 0;
	}

	private function is_banned() {
		$sql = "SELECT ip FROM banlist WHERE ip='".$_SERVER['REMOTE_ADDR']."' AND time >= DATE_SUB(NOW(), INTERVAL 1 HOUR)";
		$result = mysql_query($sql);
		if(mysql_num_rows($result) > 0) {
			echo '<img src="../gfx/error.jpg"> You are banned, try again in one hour.&nbsp;&nbsp;';
			return true;
		} else {
			if($_SESSION['fail'] > 5) {
				$sql = "INSERT INTO banlist (ip, time) VALUE('".$_SERVER['REMOTE_ADDR']."', NOW())";
				mysql_query($sql);
				return true;
			} else {
				return false;
			}
		}
	}

	public function ban_warning() {
		$_SESSION['fail']++;
		if($_SESSION['fail'] > 2) {
			$num = 7 - $_SESSION['fail'];
			echo "($num attempts left)";
		}
	}

	private function save_login($status) {
		$sql = "INSERT INTO logins (ip, user, agent, login, status) VALUES(
			'".$_SERVER['REMOTE_ADDR']."',
			'".$_SESSION['user']."', 
			'".$_SERVER['HTTP_USER_AGENT']."',
			NOW(), '$status')";

		mysql_query($sql);
	}

	private function get_last_user_id() {
		$sql = "SELECT id FROM logins WHERE user='".$_SESSION['user']."' ORDER BY id DESC LIMIT 1";
		$result = mysql_query($sql);
		$row = mysql_fetch_assoc($result);
		return $row['id'];
	}
}

?>
